<template>
  <div>
    <el-dialog
      ref="dialogRef"
      v-model="dialogVisible"
      title="维护用户角色"
      width="550px"
      append-to-body
      @close="closeDialog"
    >
      <el-table
        ref="tableRef"
        :data="tableData"
        row-key="roleId"
        empty-text="暂无数据"
        border
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center">
          <template #default="scope">
            <el-radio
              v-model="selectedIndex"
              :value="scope.row.roleId"
              @change="handleRadioChange(scope.$index, scope.row)"
            ></el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称" align="center" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, useTemplateRef, watch } from 'vue'
import { SysRole } from '@/api/system/roleTyppe'
import { ElMessage, TableInstance } from 'element-plus'
import { roleApi, userApi } from '@/api'
import { useAuthStore } from '@/stores/modules/auth'
import { SysUserRole } from '@/api/system/userType'
const authStore = useAuthStore()
const loginUser = computed(() => authStore.loginUser)

// Props定义
interface Props {
  visible: boolean
  userId: string
}

// 父组件传参
const props = withDefaults(defineProps<Props>(), {
  visible: false,
  userId: ''
})

// 对话框显示状态双向绑定
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

// Emits定义
const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
}>()

// 表格实例
const tableRef = useTemplateRef<TableInstance>('tableRef')

// 表格数据
const tableData = ref<SysRole[]>([])

// 选中的行索引
const selectedIndex = ref<string>('')

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
}

onMounted(() => {
  console.log('userId', props.userId)

  findRoleList()
})

// 查询角色列表
const findRoleList = async () => {
  roleApi
    .findRoleList(loginUser.value.companyId)
    .then((res: any) => {
      tableData.value = res || []
    })
    .catch((err: any) => {
      ElMessage.error(err || '查询角色列表失败')
    })
}

/**
 * 处理单选框变化事件
 */
const handleRadioChange = (index: string, row: SysRole) => {
  console.log('handleRadioChange', index, row)
  addUserRole(row)
  //selectedIndex.value = row.roleId
}

/**
 * 查询用户角色列表
 */
const findUserRoleList = async () => {
  selectedIndex.value = ''
  if (!props.userId) {
    return
  }
  userApi
    .findUserRoleList(props.userId)
    .then((res: any) => {
      const resData = res || []
      if (resData.length > 0) {
        selectedIndex.value = resData[0].roleId
      }
    })
    .catch((err: any) => {
      ElMessage.error(err || '查询用户角色列表失败')
    })
}

const addUserRole = async (row: SysRole) => {
  if (!props.userId) {
    ElMessage.error('请选择用户')
    return
  }
  const params: SysUserRole = {
    userId: props.userId,
    roleId: row.roleId
  }
  userApi
    .addUserRole(params)
    .then((res: any) => {
      ElMessage.success('添加用户角色成功')
      findUserRoleList()
    })
    .catch((err: any) => {
      ElMessage.error(err || '添加用户角色失败')
    })
}

watch(
  () => props.userId,
  (newVal) => {
    findUserRoleList()
  }
)
</script>

<style scoped lang="less">
:deep(.el-table__header-wrapper .el-checkbox) {
  display: none;
}
</style>
